<template>
  <div class="dept-management-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">员工管理</h1>
      <el-button 
        type="primary" 
        class="add-btn" 
        @click="openDialog"
        :loading="dialogLoading"
      >
        <el-icon><Plus /></el-icon>
        <span>新增员工</span>
      </el-button>
    </div>
    
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" class="search-form">
        <el-form-item label="查询方式">
          <el-select v-model="searchType" style="width: 100px">
            <el-option label="按 ID" value="id" />
            <el-option label="按姓名" value="name" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="searchKeyword"
            :placeholder="`请输入员工${searchType === 'id' ? 'ID' : '姓名'}`"
            clearable
            @keyup.enter="searchEmp"
            class="search-input"
          >
            <template #prefix>
              <el-icon class="search-icon"><Search /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button 
            type="primary" 
            @click="searchEmp"
            class="search-btn"
          >
            <el-icon><Search /></el-icon>
            <span>查询</span>
          </el-button>
          <el-button 
            @click="resetSearch"
            class="reset-btn"
          >
            <el-icon><Refresh /></el-icon>
            <span>重置</span>
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 数据表格区域 -->
    <el-card class="data-card">
      <div class="action-buttons" style="margin-bottom: 15px;">
        <el-button
          type="danger"
          :disabled="selectedEmpIds.length === 0"
          @click="batchDeleteEmp"
          class="action-btn delete-btn"
        >
          <el-icon><Delete /></el-icon>
          <span>批量删除</span>
        </el-button>
      </div>

      <el-table 
        :data="tableData" 
        stripe 
        border 
        fit
        highlight-current-row
        class="dept-table"
        @selection-change="handleSelectionChange"
        :loading="tableLoading"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="username" label="用户名" width="130" align="center" />
        <el-table-column prop="name" label="姓名" width="150" align="center" />
        <el-table-column label="头像" width="120" align="center">
          <template #default="scope">
            <el-avatar
              :size="50"
              :src="scope.row.image"
              @click="previewImage(scope.row.image)"
              style="cursor: pointer;"
            >
              <template #default>
                <el-icon><User /></el-icon>
              </template>
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="gender" label="性别" width="80" align="center">
          <template #default="scope">
            {{ scope.row.gender === 1 ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号" width="150" align="center" />
        <el-table-column prop="job" label="岗位" width="130" align="center">
          <template #default="scope">
            {{ jobOptions.find(item => item.value === scope.row.job)?.label || '未知岗位' }}
          </template>
        </el-table-column>
        <el-table-column prop="salary" label="薪资" width="130" align="center" />
        <el-table-column prop="entryDate" label="入职日期" width="150" align="center">
          <template #default="scope">
            {{ scope.row.entryDate || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="380">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="openEditDialog(scope.row)"
              class="action-btn edit-btn"
            >
              <el-icon><Edit /></el-icon>
              <span>修改</span>
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="deleteEmp(scope.row.id, scope.row.name)"
              class="action-btn delete-btn"
            >
              <el-icon><Delete /></el-icon>
              <span>删除</span>
            </el-button>
            <el-button
              size="small"
              type="success"
              @click="openAddExprDialog(scope.row.id)"
              class="action-btn"
            >
              <el-icon><Plus /></el-icon>
              <span>添加经历</span>
            </el-button>
            <el-button
              size="small"
              type="info"
              @click="openViewExprDialog(scope.row.id)"
              class="action-btn"
            >
              <el-icon><View /></el-icon>
              <span>查看经历</span>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          background
        />
      </div>
    </el-card>

    <!-- 新增员工对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="新增员工"
      width="500px"
      :before-close="handleDialogClose"
      class="form-dialog"
    >
      <template #title>
        <el-icon><User /></el-icon>
        <span>新增员工</span>
      </template>
      <el-form
        :model="empForm"
        :rules="rules"
        ref="empFormRef"
        label-width="100px"
        class="dialog-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="empForm.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="empForm.password" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="empForm.name" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="empForm.gender" style="width: 100%">
            <el-option label="女" :value="0" />
            <el-option label="男" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="empForm.phone" />
        </el-form-item>
        <el-form-item label="岗位" prop="job">
          <el-select v-model="empForm.job" style="width: 100%">
            <el-option
              v-for="item in jobOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="薪资" prop="salary">
          <el-input v-model.number="empForm.salary" type="number" />
        </el-form-item>
        <el-form-item label="头像" prop="image">
          <div class="upload-mode-switch">
            <el-radio-group v-model="empForm.uploadType">
              <el-radio-button label="upload">上传图片</el-radio-button>
              <el-radio-button label="link">输入链接</el-radio-button>
            </el-radio-group>
          </div>

          <div v-if="empForm.uploadType === 'upload'">
            <el-upload
              class="avatar-uploader"
              :action="uploadAction"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :headers="uploadHeaders"
            >
              <img v-if="empForm.image" :src="empForm.image" class="avatar">
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <div v-if="empForm.image" class="avatar-preview">
              <el-button type="text" @click="previewImage(empForm.image)">预览大图</el-button>
            </div>
          </div>

          <div v-else>
            <el-input
              v-model="empForm.image"
              placeholder="请输入头像图片链接"
              clearable
            >
              <template #append>
                <el-button @click="previewImage(empForm.image)">
                  预览
                </el-button>
              </template>
            </el-input>
          </div>
        </el-form-item>
        <el-form-item label="入职日期" prop="entryDate">
          <el-date-picker
            v-model="empForm.entryDate"
            type="date"
            placeholder="选择入职日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="部门 ID" prop="deptId">
          <el-input v-model.number="empForm.deptId" type="number" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false" class="dialog-btn cancel-btn">
          <el-icon><Close /></el-icon>
          <span>取消</span>
        </el-button>
        <el-button 
          type="primary" 
          @click="addEmp"
          class="dialog-btn confirm-btn"
          :loading="dialogLoading"
        >
          <el-icon><Check /></el-icon>
          <span>确定</span>
        </el-button>
      </template>
    </el-dialog>

    <!-- 修改员工对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="修改员工"
      width="500px"
      :before-close="handleDialogClose"
      class="form-dialog"
    >
      <template #title>
        <el-icon><User /></el-icon>
        <span>修改员工</span>
      </template>
      <el-form
        :model="editEmpForm"
        :rules="rules"
        ref="editEmpFormRef"
        label-width="100px"
        class="dialog-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editEmpForm.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="editEmpForm.password" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editEmpForm.name" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="editEmpForm.gender" style="width: 100%">
            <el-option label="女" :value="0" />
            <el-option label="男" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editEmpForm.phone" />
        </el-form-item>
        <el-form-item label="岗位" prop="job">
          <el-select v-model="editEmpForm.job" style="width: 100%">
            <el-option
              v-for="item in jobOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="薪资" prop="salary">
          <el-input v-model.number="editEmpForm.salary" type="number" />
        </el-form-item>
        <el-form-item label="头像" prop="image">
          <div class="upload-mode-switch">
            <el-radio-group v-model="editEmpForm.uploadType">
              <el-radio-button label="upload">上传图片</el-radio-button>
              <el-radio-button label="link">输入链接</el-radio-button>
            </el-radio-group>
          </div>

          <div v-if="editEmpForm.uploadType === 'upload'">
            <el-upload
              class="avatar-uploader"
              :action="uploadAction"
              :show-file-list="false"
              :on-success="handleEditAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :headers="uploadHeaders"
            >
              <img v-if="editEmpForm.image" :src="editEmpForm.image" class="avatar">
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <div v-if="editEmpForm.image" class="avatar-preview">
              <el-button type="text" @click="previewImage(editEmpForm.image)">预览大图</el-button>
            </div>
          </div>

          <div v-else>
            <el-input
              v-model="editEmpForm.image"
              placeholder="请输入头像图片链接"
              clearable
            >
              <template #append>
                <el-button @click="previewImage(editEmpForm.image)">
                  预览
                </el-button>
              </template>
            </el-input>
          </div>
        </el-form-item>
        <el-form-item label="入职日期" prop="entryDate">
          <el-date-picker
            v-model="editEmpForm.entryDate"
            type="date"
            placeholder="选择入职日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="部门 ID" prop="deptId">
          <el-input v-model.number="editEmpForm.deptId" type="number" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false" class="dialog-btn cancel-btn">
          <el-icon><Close /></el-icon>
          <span>取消</span>
        </el-button>
        <el-button 
          type="primary" 
          @click="updateEmp"
          class="dialog-btn confirm-btn"
          :loading="dialogLoading"
        >
          <el-icon><Check /></el-icon>
          <span>确定</span>
        </el-button>
      </template>
    </el-dialog>

    <!-- 添加/编辑工作经历对话框 -->
    <el-dialog
      v-model="exprDialogVisible"
      :title="exprForm.id ? '编辑工作经历' : isBatchMode ? '批量添加工作经历' : '添加工作经历'"
      width="500px"
      class="form-dialog"
    >
      <template #title>
        <el-icon><Briefcase /></el-icon>
        <span>{{ exprForm.id ? '编辑工作经历' : isBatchMode ? '批量添加工作经历' : '添加工作经历' }}</span>
      </template>

      <div v-if="!isBatchMode && !exprForm.id" style="margin-bottom: 15px; display: flex; justify-content: flex-end;">
        <el-button type="primary" @click="toggleBatchMode" class="action-btn">
          切换到批量添加模式
        </el-button>
      </div>

      <div v-if="isBatchMode" style="margin-bottom: 15px; display: flex; justify-content: space-between; align-items: center;">
        <div style="display: flex; align-items: center;">
          <el-input-number
            v-model="batchSize"
            :min="1"
            :max="10"
            label="添加数量"
          />
          <el-button
            type="primary"
            @click="addMoreBatchForms"
            style="margin-left: 10px;"
            class="action-btn"
          >
            添加表单
          </el-button>
        </div>
        <el-button type="primary" @click="toggleBatchMode" class="action-btn">
          切换到单条添加模式
        </el-button>
      </div>

      <el-scrollbar :height="isBatchMode ? '400px' : 'auto'">
        <!-- 单条表单模式 -->
        <el-form
          v-if="!isBatchMode"
          :model="exprForm"
          label-width="100px"
          class="dialog-form"
        >
          <el-form-item label="公司名称" prop="company">
            <el-input v-model="exprForm.company" />
          </el-form-item>
          <el-form-item label="职位" prop="job">
            <el-input v-model="exprForm.job" />
          </el-form-item>
          <el-form-item label="开始日期" prop="begin">
            <el-date-picker
              v-model="exprForm.begin"
              type="date"
              placeholder="选择开始日期"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="结束日期" prop="end">
            <el-date-picker
              v-model="exprForm.end"
              type="date"
              placeholder="选择结束日期"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
        </el-form>

        <!-- 批量表单模式 -->
        <div v-if="isBatchMode">
          <el-form
            v-for="(form, index) in batchExprForms"
            :key="index"
            :model="form"
            label-width="100px"
            class="dialog-form"
            style="margin-bottom: 20px; border: 1px solid #eee; padding: 15px; border-radius: 4px;"
          >
            <div style="display: flex; justify-content: flex-end; margin-bottom: 10px;">
              <el-button
                size="small"
                type="danger"
                @click="removeBatchForm(index)"
                :disabled="batchExprForms.length <= 1"
                class="action-btn delete-btn"
              >
                <el-icon><Delete /></el-icon>
                <span>删除</span>
              </el-button>
            </div>
            <el-form-item label="公司名称" prop="company">
              <el-input v-model="form.company" />
            </el-form-item>
            <el-form-item label="职位" prop="job">
              <el-input v-model="form.job" />
            </el-form-item>
            <el-form-item label="开始日期" prop="begin">
              <el-date-picker
                v-model="form.begin"
                type="date"
                placeholder="选择开始日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="结束日期" prop="end">
              <el-date-picker
                v-model="form.end"
                type="date"
                placeholder="选择结束日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-form>
        </div>
      </el-scrollbar>

      <template #footer>
        <el-button @click="exprDialogVisible = false" class="dialog-btn cancel-btn">
          <el-icon><Close /></el-icon>
          <span>取消</span>
        </el-button>
        <el-button type="primary" @click="saveExpr" class="dialog-btn confirm-btn">
          <el-icon><Check /></el-icon>
          <span>保存</span>
        </el-button>
      </template>
    </el-dialog>

    <!-- 查看工作经历对话框 -->
    <el-dialog v-model="viewExprDialogVisible" title="工作经历" width="60%" class="form-dialog">
      <template #title>
        <el-icon><Briefcase /></el-icon>
        <span>工作经历</span>
      </template>
      <el-table :data="exprs" border style="width: 100%" class="dept-table">
        <el-table-column prop="company" label="公司" width="200" />
        <el-table-column prop="job" label="职位" width="200" />
        <el-table-column label="工作时间" width="500">
          <template #default="scope">
            {{ scope.row.begin }} 至 {{ scope.row.end }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="170">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="openEditExprForm(scope.row)"
              class="action-btn edit-btn"
            >
              <el-icon><Edit /></el-icon>
              <span>编辑</span>
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="deleteExpr(scope.row.id)"
              class="action-btn delete-btn"
            >
              <el-icon><Delete /></el-icon>
              <span>删除</span>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import type { EmpModelArray } from '@/api/model/model'
import axios from 'axios'
import {
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElDatePicker,
  ElMessage,
  ElPagination,
  ElMessageBox,
  ElSelect,
  ElOption,
  ElButton,
  ElTable,
  ElTableColumn,
  ElUpload,
  ElAvatar,
  ElImage,
  ElInputNumber,
  ElScrollbar,
  ElRadioGroup,
  ElRadioButton,
  ElLoading
} from 'element-plus'
import { 
  Plus, Search, Refresh, Edit, Delete, 
  User, Close, Check, View, Briefcase
} from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'

// 存储所有员工数据
const allEmpData = ref<EmpModelArray>([])

// 分页相关数据
const currentPage = ref(1)
const pageSize = ref(5)

// 查询相关
const searchKeyword = ref('')
const searchType = ref('id')

// 选择功能
const selectedEmpIds = ref<number[]>([])

// 上传相关配置
const uploadAction = ref('http://localhost:8080/upload')
const uploadHeaders = ref({
  Authorization: 'Bearer ' + localStorage.getItem('token') || ''
})

// 计算属性
const tableData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return allEmpData.value.slice(start, end)
})

const totalPages = computed(() => {
  return Math.ceil(allEmpData.value.length / pageSize.value)
})

const total = computed(() => {
  return allEmpData.value.length
})

// 数据加载
const loadAllData = async () => {
  try {
    const result = await axios.get('http://localhost:8080/emp')
    const processedData = result.data.data.map((emp: any) => ({
      id: emp.id,
      username: emp.username,
      password: emp.password,
      name: emp.name,
      gender: emp.gender,
      phone: emp.phone,
      job: emp.job,
      salary: emp.salary,
      image: emp.image,
      entryDate: emp.entryDate ? new Date(emp.entryDate).toISOString().slice(0, 10) : null,
      deptId: emp.deptId,
      createTime: emp.createTime ? new Date(emp.createTime).toISOString().slice(0, 19).replace('T', ' ') : null,
      updateTime: emp.updateTime ? new Date(emp.updateTime).toISOString().slice(0, 19).replace('T', ' ') : null
    }))
    allEmpData.value = processedData || []
    selectedEmpIds.value = []
  } catch (error) {
    console.error('加载员工数据失败', error)
    ElMessage.error('加载员工数据失败')
  }
}

// 查询功能
const searchEmp = async () => {
  if (!searchKeyword.value.trim()) {
    await loadAllData()
    currentPage.value = 1
    return
  }

  try {
    if (searchType.value === 'id') {
      const result = await axios.get(`http://localhost:8080/emp/${searchKeyword.value}`)
      allEmpData.value = result.data.data ? [result.data.data] : []
      if (allEmpData.value.length === 0) {
        ElMessage.warning('未找到匹配的员工')
      }
    } else {
      const encodedName = encodeURIComponent(searchKeyword.value)
      const result = await axios.get(`http://localhost:8080/emp/name/${encodedName}`)
      allEmpData.value = result.data.data || []
      if (allEmpData.value.length === 0) {
        ElMessage.warning('未找到匹配的员工')
      }
    }
    currentPage.value = 1
  } catch (error) {
    console.error('查询员工失败', error)
    ElMessage.error('查询员工失败')
  }
}

const resetSearch = async () => {
  searchKeyword.value = ''
  await loadAllData()
  currentPage.value = 1
}

// 对话框控制
const dialogVisible = ref(false)
const editDialogVisible = ref(false)
const dialogLoading = ref(false)
const tableLoading = ref(false)

// 表单数据
const empForm = ref({
  username: '',
  password: '123456',
  name: '',
  gender: 0,
  phone: '',
  job: 0,
  salary: 0,
  image: '',
  entryDate: '',
  deptId: 0,
  createTime: '',
  updateTime: '',
  uploadType: 'upload'
})

const editEmpForm = ref({
  id: 0,
  username: '',
  password: '',
  name: '',
  gender: 0,
  phone: '',
  job: 0,
  salary: 0,
  image: '',
  entryDate: '',
  deptId: 0,
  createTime: '',
  updateTime: '',
  uploadType: 'upload'
})

// 表单验证规则
const rules = ref({
  username: [
    { required: true, message: '用户名不能为空', trigger: 'blur' },
    { max: 20, message: '用户名最长 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { max: 50, message: '密码最长 50 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '姓名不能为空', trigger: 'blur' },
    { max: 10, message: '姓名最长 10 个字符', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '性别不能为空', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '手机号不能为空', trigger: 'blur' },
    { len: 11, message: '手机号必须为 11 位', trigger: 'blur' }
  ],
  job: [
    { required: true, message: '工作岗位不能为空', trigger: 'change' }
  ],
  salary: [
    { required: true, message: '薪资不能为空', trigger: 'blur' }
  ],
  entryDate: [
    { required: true, message: '入职日期不能为空', trigger: 'change' }
  ],
  deptId: [
    { required: true, message: '部门 id 不能为空', trigger: 'change' }
  ]
})

// 头像上传处理
const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
  let imageUrl = ''

  if (response?.data?.url) { // 格式1: { data: { url: "..." } }
    imageUrl = response.data.url
  } else if (response?.url) { // 格式2: { url: "..." }
    imageUrl = response.url
  } else if (response?.data) { // 格式3: 直接返回URL字符串
    imageUrl = response.data
  } else if (file?.response?.url) { // 格式4: file对象中包含响应
    imageUrl = file.response.url
  }

  if (imageUrl) {
    empForm.value.image = imageUrl
    ElMessage.success('上传成功')
  } else {
    console.error('无法解析的响应格式:', response)
    ElMessage.error('上传成功，但无法解析返回的图片地址')
  }
}

const handleEditAvatarSuccess: UploadProps['onSuccess'] = (response) => {
  let imageUrl = ''

  if (response?.data?.url) {
    imageUrl = response.data.url
  } else if (response?.url) {
    imageUrl = response.url
  } else if (response?.data) {
    imageUrl = response.data
  } else if (file?.response?.url) {
    imageUrl = file.response.url
  }

  if (imageUrl) {
    editEmpForm.value.image = imageUrl
    ElMessage.success('上传成功')
  } else {
    console.error('无法解析的响应格式:', response)
    ElMessage.error('上传成功，但无法解析返回的图片地址')
  }
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (file) => {
  const isImage = ['image/jpeg', 'image/png', 'image/gif'].includes(file.type)
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传 JPG/PNG/GIF 格式的图片!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }

  return isImage && isLt2M
}

// 图片预览
const previewImage = (url: string) => {
  if (!url) {
    ElMessage.warning('暂无图片可预览')
    return
  }
  window.open(url, '_blank')
}

// 对话框操作
const openDialog = () => {
  const now = new Date().toISOString().slice(0, 19).replace('T', ' ')
  empForm.value = {
    username: '',
    password: '123456',
    name: '',
    gender: 0,
    phone: '',
    job: 0,
    salary: 0,
    image: '',
    entryDate: '',
    deptId: 0,
    createTime: now,
    updateTime: now,
    uploadType: 'upload'
  }
  dialogVisible.value = true
}

const openEditDialog = (emp: any) => {
  editEmpForm.value = {
    id: emp.id,
    username: emp.username,
    password: emp.password,
    name: emp.name,
    gender: emp.gender,
    phone: emp.phone,
    job: emp.job,
    salary: emp.salary,
    image: emp.image,
    entryDate: emp.entryDate,
    deptId: emp.deptId,
    createTime: emp.createTime,
    updateTime: emp.updateTime,
    uploadType: emp.image?.startsWith('http') ? 'link' : 'upload'
  }
  editDialogVisible.value = true
}

const jobOptions = ref([
  { value: 1, label: '项目经理' },
  { value: 2, label: '前端开发' },
  { value: 3, label: '后端开发' },
  { value: 4, label: 'UI设计师' },
  { value: 5, label: '测试工程师' },
  { value: 6, label: '产品经理' },
  { value: 7, label: '数据分析师' },
  { value: 8, label: '运维工程师' }
])

// CRUD操作
const addEmp = async () => {
  dialogLoading.value = true
  try {
    const formData = {
      ...empForm.value,
      image: empForm.value.image || '', // 确保图片字段存在
      gender: Number(empForm.value.gender),
      job: Number(empForm.value.job),
      salary: Number(empForm.value.salary),
      deptId: Number(empForm.value.deptId)
    }

    const response = await axios.post('http://localhost:8080/emp', formData)
    ElMessage.success('员工添加成功')
    dialogVisible.value = false
    await loadAllData()
    currentPage.value = 1
  } catch (error) {
    console.error('员工添加失败', error)
    ElMessage.error('员工添加失败')
  } finally {
    dialogLoading.value = false
  }
}

const updateEmp = async () => {
  dialogLoading.value = true
  try {
    const formData = {
      ...editEmpForm.value,
      image: editEmpForm.value.image || '', // 确保图片字段存在
      gender: Number(editEmpForm.value.gender),
      job: Number(editEmpForm.value.job),
      salary: Number(editEmpForm.value.salary),
      deptId: Number(editEmpForm.value.deptId),
      entryDate: editEmpForm.value.entryDate,
      updateTime: new Date().toISOString().slice(0, 19).replace('T', ' ')
    }

    const response = await axios.put('http://localhost:8080/emp', formData)
    ElMessage.success('员工修改成功')
    editDialogVisible.value = false
    await loadAllData()
  } catch (error) {
    console.error('员工修改失败:', error)
    let errorMsg = '员工修改失败'
    if (error.response) {
      errorMsg = error.response.data?.message ||
        error.response.data?.error ||
        error.response.data?.msg ||
        error.response.statusText ||
        `请求失败，状态码: ${error.response.status}`
      if (error.response.data?.errors) {
        errorMsg = Object.values(error.response.data.errors).join(', ')
      }
    } else if (error.message) {
      errorMsg = error.message
    }
    ElMessage.error(errorMsg)
  } finally {
    dialogLoading.value = false
  }
}

// 分页操作
const handleCurrentChange = (page: number) => {
  currentPage.value = page
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
}

// 选择操作
const handleSelectionChange = (selection: any[]) => {
  selectedEmpIds.value = selection.map(item => item.id)
}

// 删除操作
const deleteEmp = (id: number, name: string) => {
  ElMessageBox.confirm(
    `确定要删除员工【${name}】吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      center: true,
      showClose: false
    }
  ).then(async () => {
    try {
      const loading = ElLoading.service({
        lock: true,
        text: '正在删除...',
        background: 'rgba(0, 0, 0, 0.1)'
      })
      
      await axios.delete(`http://localhost:8080/emp/${id}`)
      ElMessage.success('员工删除成功')
      await loadAllData()
      
      // 如果删除后当前页没有数据，回到前一页
      if ((currentPage.value - 1) * pageSize.value >= total.value - 1) {
        currentPage.value = Math.max(1, currentPage.value - 1)
      }
      
      loading.close()
    } catch (error) {
      console.error('员工删除失败', error)
      ElMessage.error('员工删除失败')
    }
  }).catch(() => {})
}

const batchDeleteEmp = () => {
  if (selectedEmpIds.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }

  const selectedNames = tableData.value
    .filter(emp => selectedEmpIds.value.includes(emp.id))
    .map(emp => emp.name)
    .join('、')

  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedEmpIds.value.length} 名员工【${selectedNames}】吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      center: true,
      showClose: false
    }
  ).then(async () => {
    try {
      const loading = ElLoading.service({
        lock: true,
        text: '正在删除...',
        background: 'rgba(0, 0, 0, 0.1)'
      })
      
      const deletePromises = selectedEmpIds.value.map(id =>
        axios.delete(`http://localhost:8080/emp/${id}`)
      )
      await Promise.all(deletePromises)
      ElMessage.success(`成功删除 ${selectedEmpIds.value.length} 名员工`)
      await loadAllData()
      selectedEmpIds.value = []
      if ((currentPage.value - 1) * pageSize.value >= total.value - 1) {
        currentPage.value = Math.max(1, currentPage.value - 1)
      }
      
      loading.close()
    } catch (error) {
      console.error('批量删除失败', error)
      ElMessage.error('批量删除失败')
    }
  }).catch(() => {})
}

// 工作经历相关状态
const exprDialogVisible = ref(false)
const viewExprDialogVisible = ref(false)
const currentEmpId = ref(0)
const exprs = ref<any[]>([])
const batchExprForms = ref<any[]>([])
const batchSize = ref(1)
const isBatchMode = ref(false)

const exprForm = ref({
  id: 0,
  empId: 0,
  begin: '',
  end: '',
  company: '',
  job: ''
})

// 打开添加工作经历对话框
const openAddExprDialog = (empId: number) => {
  currentEmpId.value = empId
  exprForm.value = {
    id: 0,
    empId: empId,
    begin: '',
    end: '',
    company: '',
    job: ''
  }
  batchExprForms.value = [{
    id: 0,
    empId: empId,
    begin: '',
    end: '',
    company: '',
    job: ''
  }]
  isBatchMode.value = false
  exprDialogVisible.value = true
}

// 切换批量模式
const toggleBatchMode = () => {
  isBatchMode.value = !isBatchMode.value
  if (isBatchMode.value && batchExprForms.value.length === 0) {
    batchExprForms.value = [{
      id: 0,
      empId: currentEmpId.value,
      begin: '',
      end: '',
      company: '',
      job: ''
    }]
  }
}

// 添加更多批量表单
const addMoreBatchForms = () => {
  for (let i = 0; i < batchSize.value; i++) {
    batchExprForms.value.push({
      id: 0,
      empId: currentEmpId.value,
      begin: '',
      end: '',
      company: '',
      job: ''
    })
  }
}

// 移除一条批量表单
const removeBatchForm = (index: number) => {
  if (batchExprForms.value.length > 1) {
    batchExprForms.value.splice(index, 1)
  } else {
    ElMessage.warning('至少保留一条工作经历')
  }
}

// 打开查看工作经历对话框
const openViewExprDialog = async (empId: number) => {
  currentEmpId.value = empId
  try {
    const res = await axios.get(`http://localhost:8080/expr/emp/${empId}`)
    exprs.value = res.data.data || []
    viewExprDialogVisible.value = true
  } catch (error) {
    console.error('加载工作经历失败', error)
    ElMessage.error('加载工作经历失败')
  }
}

// 保存工作经历
const saveExpr = async () => {
  try {
    if (isBatchMode.value) {
      // 批量保存
      await axios.post('http://localhost:8080/expr/batch', batchExprForms.value)
      ElMessage.success(`成功添加${batchExprForms.value.length}条工作经历`)
    } else {
      // 单条保存
      if (exprForm.value.id) {
        await axios.put('http://localhost:8080/expr', exprForm.value)
        ElMessage.success('工作经历更新成功')
      } else {
        await axios.post('http://localhost:8080/expr', exprForm.value)
        ElMessage.success('工作经历添加成功')
      }
    }
    exprDialogVisible.value = false
    await openViewExprDialog(currentEmpId.value)
  } catch (error) {
    console.error('保存工作经历失败', error)
    ElMessage.error('保存工作经历失败')
  }
}

// 打开编辑工作经历表单
const openEditExprForm = (expr: any) => {
  exprForm.value = {
    ...expr,
    begin: expr.begin ? new Date(expr.begin).toISOString().slice(0, 10) : '',
    end: expr.end ? new Date(expr.end).toISOString().slice(0, 10) : ''
  }
  isBatchMode.value = false
  exprDialogVisible.value = true
}

// 删除工作经历
const deleteExpr = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定删除这条工作经历吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      center: true,
      showClose: false
    })
    await axios.delete(`http://localhost:8080/expr/${id}`)
    ElMessage.success('删除成功')
    await openViewExprDialog(currentEmpId.value)
  } catch (error) {
    console.error('删除失败', error)
  }
}

// 对话框关闭前处理
const handleDialogClose = (done: () => void) => {
  done()
}

// 初始化
onMounted(() => {
  loadAllData()
})
</script>

<style scoped>
/* 引入Tailwind CSS工具类 */
@layer utilities {
  .content-auto {
    content-visibility: auto;
  }
  .transition-all-300 {
    transition: all 0.3s ease;
  }
  .shadow-hover {
    transition: box-shadow 0.3s ease, transform 0.3s ease;
  }
  .shadow-hover:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    transform: translateY(-1px);
  }
}

/* 页面整体样式 */
.dept-management-container {
  padding: 20px;
  background-color: #f8fafc;
  min-height: 100vh;
}

/* 页面头部样式 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #334155;
  margin: 0;
  display: flex;
  align-items: center;
}

.page-title::before {
  content: '';
  display: inline-block;
  width: 4px;
  height: 24px;
  background-color: #4f46e5;
  margin-right: 10px;
  border-radius: 2px;
}

/* 搜索卡片样式 */
.search-card {
  border-radius: 8px;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
  transition: all 0.3s ease;
}

.search-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.search-form {
  display: flex;
  align-items: center;
  padding: 16px 20px;
}

.search-input {
  width: 280px;
}

.search-input :deep(.el-input__wrapper) {
  border-radius: 6px;
  padding-left: 10px;
  transition: all 0.2s;
}

.search-input :deep(.el-input__wrapper):hover {
  border-color: #4f46e5;
}

.search-icon {
  color: #94a3b8;
}

.search-btn,
.reset-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 8px 16px;
  border-radius: 6px;
  transition: all 0.2s;
}

.search-btn {
  background-color: #4f46e5;
  border-color: #4f46e5;
  color: white;
}

.search-btn:hover {
  background-color: #4338ca;
  border-color: #4338ca;
}

.reset-btn {
  margin-left: 10px;
}

.reset-btn:hover {
  color: #4f46e5;
  border-color: #4f46e5;
}

/* 新增按钮样式 */
.add-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  background-color: #10b981;
  border-color: #10b981;
  padding: 8px 16px;
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.2s;
}

.add-btn:hover {
  background-color: #059669;
  border-color: #059669;
  transform: translateY(-1px);
}

.add-btn el-icon {
  margin-right: 6px;
}

/* 数据卡片样式 */
.data-card {
  border-radius: 8px;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  height: calc(100vh - 220px); /* 根据实际布局调整高度 */
}

.data-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.dept-table {
  flex: 1;
  overflow: auto;
}

.dept-table :deep(.el-table__header) {
  background-color: #f1f5f9;
}

.dept-table :deep(.el-table__header th) {
  font-weight: 600;
  color: #334155;
}

.dept-table :deep(.el-table__row) {
  transition: all 0.2s;
}

.dept-table :deep(.el-table__row:hover) {
  background-color: #f8fafc;
}

.dept-table :deep(.el-table__cell) {
  padding: 12px 0;
}

/* 操作按钮样式 */
.action-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 6px 12px;
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.2s;
  margin: 0 4px;
}

.action-btn el-icon {
  margin-right: 4px;
}

.edit-btn {
  background-color: #e0f2fe;
  border-color: #e0f2fe;
  color: #0284c7;
}

.edit-btn:hover {
  background-color: #bae6fd;
  border-color: #bae6fd;
}

.delete-btn {
  background-color: #fee2e2;
  border-color: #fee2e2;
  color: #ef4444;
}

.delete-btn:hover {
  background-color: #fecaca;
  border-color: #fecaca;
}

/* 分页样式 */
.pagination-container {
  padding: 16px 20px;
  display: flex;
  justify-content: flex-end;
  background-color: white;
  border-top: 1px solid #e2e8f0;
}

/* 对话框样式 */
.form-dialog {
  border-radius: 8px;
  overflow: hidden;
}

.form-dialog :deep(.el-dialog__header) {
  background-color: #f8fafc;
  padding: 16px 20px;
  border-bottom: 1px solid #e2e8f0;
}

.form-dialog :deep(.el-dialog__title) {
  font-size: 18px;
  font-weight: 600;
  color: #334155;
  display: flex;
  align-items: center;
}

.form-dialog :deep(.el-dialog__title) el-icon {
  margin-right: 8px;
  color: #4f46e5;
}

.form-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.dialog-form :deep(.el-form-item) {
  margin-bottom: 20px;
}

.dialog-form :deep(.el-form-item__label) {
  font-weight: 500;
  color: #475569;
}

.dialog-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 8px 16px;
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.2s;
}

.cancel-btn {
  border: 1px solid #e2e8f0;
  color: #64748b;
}

.cancel-btn:hover {
  border-color: #4f46e5;
  color: #4f46e5;
}

.confirm-btn {
  background-color: #4f46e5;
  border-color: #4f46e5;
  color: white;
}

.confirm-btn:hover {
  background-color: #4338ca;
  border-color: #4338ca;
}

/* 头像上传样式 */
.avatar-uploader :deep(.el-upload) {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-preview {
  margin-top: 10px;
  text-align: center;
}

.upload-mode-switch {
  margin-bottom: 10px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}
</style>